import store from "@/store";
import { listUserMenu } from "@/api/user";
import Router from "@/router/index";

const state = {
    token: sessionStorage.getItem("token") || "",
    userName: sessionStorage.getItem("userName") || "",
    userId: sessionStorage.getItem("userId") || "",
    permisstionRoutes: [],
};
const mutations = {
    SET_TOKEN(state, token) {
        sessionStorage.setItem("token", token);
        state.token = token;
    },
    SET_USERNAME(state, userName) {
        sessionStorage.setItem("userName", userName);
        state.userName = userName;
    },
    SET_USERID(state, id) {
        sessionStorage.setItem("userId", id);
        state.userId = id;
    },
    SET_PERMISSTION_ROUTES(state, permisstionRoutes) {
        state.permisstionRoutes = permisstionRoutes;
    },
};

const actions = {
    /**
     *
     * @param {动态添加侧边栏路由} param0
     */
    GenerateRoutes({ commit, state }) {
        return new Promise((resolve, reject) => {
            listUserMenu({ userId: state.userId }).then((res) => {
                if (res.data.success) {
                    const routes = res.data.data;

                    commit("SET_PERMISSTION_ROUTES", routes);
                    routerPackag(routes);
                    resolve(routes);
                } else {
                    reject(res);
                }
            });
        });
    },
    /**
     *
     * @param {退出登录} commit
     * @returns
     */
    logout({ commit }) {
        return new Promise((resolve, reject) => {
            store.commit("app/ADD_VISITED_VIEW", []);
            commit("SET_USERNAME", "");
            commit("SET_TOKEN", "");
            commit("SET_PERMISSTION_ROUTES", []);
            sessionStorage.clear();
            resolve();
        });
    },
};

/**
 *
 * @param {动态添加路由} routers
 */
const routerPackag = (routers) => {
    routers.map((itemRouter) => {
        Router.addRoute("baseLayout", {
            path: `${itemRouter.viewPath}`,
            name: itemRouter.code,
            component: () =>
                import (`@/views/${itemRouter.code}/index.vue`),
            meta: { title: itemRouter.name },
        });
        if (itemRouter.children) {
            itemRouter.children.map((item) => {
                Router.addRoute(itemRouter.code, {
                    path: `${item.viewPath}`,
                    name: item.code,
                    component: () =>
                        import (`@/views/${itemRouter.code}/${item.code}/index.vue`),
                    meta: { title: item.name },
                });
                return item;
            });
        }

        return itemRouter;
    });
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};